package com.example.projectmanagement.interceptor;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class ApiMonitorInterceptor implements HandlerInterceptor {
    
    // 存储API调用统计信息的线程安全Map
    private static final ConcurrentHashMap<String, ApiEndpointStatistics> apiStats = new ConcurrentHashMap<>();
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 记录请求开始时间
        request.setAttribute("startTime", System.currentTimeMillis());
        return true;
    }
    
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        long startTime = (Long) request.getAttribute("startTime");
        long endTime = System.currentTimeMillis();
        long duration = endTime - startTime;
        
        String url = request.getRequestURI();
        String method = request.getMethod();
        int statusCode = response.getStatus();
        
        String apiEndpointKey = method + ":" + url;
        
        // 更新API统计信息
        apiStats.compute(apiEndpointKey, (key, stats) -> {
            if (stats == null) {
                stats = new ApiEndpointStatistics();
                stats.setUrl(url);
                stats.setMethod(method);
            }
            
            stats.incrementRequestCount();
            stats.updateResponseTime(duration);
            
            if (statusCode >= 400) {
                stats.incrementErrorCount();
            }
            
            stats.setLastAccessTime(LocalDateTime.now());
            
            return stats;
        });
    }
    
    /**
     * 获取所有API统计信息
     */
    public static ConcurrentHashMap<String, ApiEndpointStatistics> getApiStats() {
        return apiStats;
    }
    
    /**
     * 重置所有API统计信息
     */
    public static void resetApiStats() {
        apiStats.clear();
    }
    
    /**
     * 根据时间重置API统计信息
     */
    public static void resetApiStatsByTime(int hours) {
        LocalDateTime cutoffTime = LocalDateTime.now().minusHours(hours);
        apiStats.entrySet().removeIf(entry -> entry.getValue().getLastAccessTime().isBefore(cutoffTime));
    }
}